package com.kc.demo.kcapidemo.demo;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kc.demo.kcapidemo.utils.AESUtil;
import com.kc.demo.kcapidemo.utils.HttpClientUtil;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version v1.0
 * @类描述：
 * @项目名称：
 * @包名： com.kc.demo.kcapidemo.demo
 * @类名称：KcHelmetDemo
 * @创建人：YIHANG.XU
 * @创建时间：2021/8/239:13 上午
 * @修改人：YIHANG.XU
 * @修改时间：2021/8/239:13 上午
 * @修改备注：
 * @Copyright
 */
public class KcHelmetDemo {
    private static Map<String, String> keyMap = new HashMap<>();

    private static String key = "";

    public static void main(String[] args) {
        RestTemplate sllRestTemplate = null;
        try {
            sllRestTemplate = HttpClientUtil.getSllRestTemplate();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //login(sllRestTemplate);
        //getUserInfo(sllRestTemplate);
        // getFaceDb(sllRestTemplate);
        //getOrderId(sllRestTemplate);
        //faceDb(sllRestTemplate, 11);
        //addFace(sllRestTemplate);
        // getFaceDBList(sllRestTemplate);
        // delFace(sllRestTemplate);
        //faceAuthentication(sllRestTemplate);
        // onlineEquipment(sllRestTemplate);
        //pushMasge(sllRestTemplate, 2);

    }
    public static void to(RestTemplate sllRestTemplate){

        String aa = "https://dev-cloud-services.haier-ioc.com/cloudApi/order/secondNode/getHandle";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("handle", "1");

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
        ResponseEntity<String> exchange = sllRestTemplate.exchange(aa, HttpMethod.POST, httpEntity, String.class);
        String body = exchange.getBody();
        System.err.println(body);
    }

    //登录系统
    public static void login(RestTemplate sllRestTemplate) {

        String loginUrl = "https://33.192.75.46:5558/helmetProxy/login";


        String userName = "admin";  //账号
        String password = "Kc123123";  //密码
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);

            MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
            form.add("username", userName);
            form.add("password", password);
            form.add("lang", "zh_CN");
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
            ResponseEntity<String> exchange = sllRestTemplate.exchange(loginUrl, HttpMethod.POST, httpEntity, String.class);
            HttpHeaders headers1 = exchange.getHeaders();
            List<String> list = headers1.get("Set-Cookie");
            String session = list.get(1);
            String sessionAttName = "SESSION=";
            key = session.substring(session.indexOf(sessionAttName) + sessionAttName.length(), session.indexOf(";", session.indexOf(sessionAttName) + sessionAttName.length()));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------
    //-----------------------使用    平台    账号   登录---------------------------------------------
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------

    /**
     * 获取登录用户信息
     * 基本不需要使用
     *
     * @param restTemplate
     */
    public static void getUserInfo(RestTemplate restTemplate) {
        String userInfoUrl = "https://39.108.64.200:5558/helmetProxy/getCurrentUser?lang=zh_CN";
        try {

            HttpHeaders headers = new HttpHeaders();
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> requestEntity = new HttpEntity<String>(null, headers);
            ResponseEntity<String> response = restTemplate.exchange(userInfoUrl, HttpMethod.GET, requestEntity, String.class);
            String body = response.getBody();
            System.err.println(body);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取存在的人像库数据库
     * 请求参数： type 库类型 0 人脸库，1 车牌库 2. 整件库
     * orgId 机构编号 默认是空
     * lang  语言
     * 响应参数：
     * {
     * "message":"请求成功",
     * "data":[
     * {
     * "id":688,  //人像库id
     * "name":"测试数据库", // 人像库名字
     * "creator":"admin", // 人像库创建
     * "createAt":"2021-08-23 13:59:03",  // 创建时间
     * "type":0,
     * "orgId":616,  // 机构id
     * "orgName":"上海保安公司",  // 机构名字
     * "compType":1,  // 库类型 模式人像库是1
     * "user":null,
     * "popup":1,
     * "dataCount":0,// 存在多少人
     * "unreviewedCount":null,
     * "relationDb":null,
     * "busType":null,
     * "bindUser":null,
     * "hr":null,
     * "temperature":null,
     * "selected":false
     * }
     * ],
     * "code":200,
     * "total":null,
     * "webOnline":null
     * }
     */
    public static void getFaceDb(RestTemplate restTemplate) {
        String getFaceDb = "https://39.108.64.200:5558/helmetBusiness/api/db/select";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);

        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("type", 0);
        form.add("orgId", "");
        form.add("lang", "zh_CN");
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(getFaceDb, HttpMethod.POST, httpEntity, String.class);
        String body = exchange.getBody();
        System.err.println(body);

    }

    /**
     * 查询所有机构
     * {
     * "message":"请求成功",
     * "data":[
     * {
     * "id":16,
     * "parentId":0,
     * "pinyin":null,
     * "name":"xx市公安局",
     * "remark":null,
     * "longitude":"113.940536",
     * "latitude":"22.548228",
     * "address":"高新中一道九号",
     * "index":"1",
     * "status":"1",
     * "level":1,
     * "parentName":null,
     * "type":"2",
     * "verificationCode":null,
     * "children":[
     * {
     * "id":615,  id
     * "parentId":16,   机构id ********
     * "pinyin":"ShenzhenKcDemonstration",
     * "name":"深圳光启头盔演示",
     * "remark":null,
     * "longitude":"113.940536",  经纬度
     * "latitude":"22.548228",
     * "address":"广东省深圳市南山区粤海街道软件大厦", 地区
     * "index":"1",
     * "status":"1",
     * "level":2,
     * "parentName":"xx市公安局",   机构名字
     * "type":"1",
     * "verificationCode":"123456",
     * "children":[
     * {
     * "id":621,
     * "parentId":615,
     * "pinyin":"Testing agency 1",
     * "name":"测试机构1",
     * "remark":null,
     * "longitude":"113.951866",
     * "latitude":"22.556789",
     * "address":"广东省深圳市南山区西丽街道松坪村苑",
     * "index":"1",
     * "status":"1",
     * "level":3,
     * "parentName":"深圳光启头盔演示",
     * "type":"1",
     * "verificationCode":"123456",
     * "children":[
     * <p>
     * ],
     * "users":null,
     * "devices":null
     * }
     * ],
     * "users":null,
     * "devices":null
     * }
     * ],
     * "users":null,
     * "devices":null
     * }
     * ],
     * "code":200,
     * "total":null,
     * "webOnline":null
     * }
     *
     * @param restTemplate
     * @return
     */
    public static String getOrderId(RestTemplate restTemplate) {
        String orderUrl = "https://39.108.64.200:5558/base/org/userBelongsOrg?id=16&lang=zh_CN";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> requestEntity = new HttpEntity<String>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(orderUrl, HttpMethod.GET, requestEntity, String.class);
        String body = response.getBody();
        //获取总机构下面的子机构
        JSONArray data = JSON.parseObject(body).getJSONArray("data");
        JSONObject o = (JSONObject) data.get(0);
        JSONArray children = o.getJSONArray("children");
        JSONObject jsonObject = children.getJSONObject(0);
        int id = jsonObject.getIntValue("id");
        System.out.println(id);
        System.err.println(body);

        return id + "";
    }

    /**
     * 使用光启算法创建人脸库
     * 请求数据
     * name: dssd
     * orgId: 616
     * type: 0
     * compType: 1
     * popup: 1
     * lang: zh_CN
     * 返回数据
     * *       {"code":200,"message":"删除成功","data":null}
     */
    public static void faceDb(RestTemplate restTemplate, int orgId) {
        String dbUrl = "https://39.108.64.200:5558/helmetBusiness/api/db/save";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("name", "测试数据库");
        form.add("orgId", 616);
        //人脸库
        form.add("type", 0);
        //默认值
        form.add("compType", 1);
        form.add("popup", 1);
        form.add("lang", "zh_CN");
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(dbUrl, HttpMethod.POST, httpEntity, String.class);
        String body = exchange.getBody();
        System.err.println(body);

    }

    /**
     * 人脸库添加数据
     * 请求数据
     * <p>
     * file: (二进制)
     * personName: ces
     * sex: 1
     * personId: 934434343
     * dbId: 688
     * label: 2
     * deptName:
     * <p>
     * 返回数据
     * {"code":200,"message":"删除成功","data":null}
     */
    public static void addFace(RestTemplate restTemplate) {
        String addFace = "https://39.108.64.200:5558/helmetBusiness/api/st/synPic";
        String fileName = "/Users/xuyihang/Downloads/测试照片.jpg";
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        form.add("file", new FileSystemResource(fileName));
        form.add("personName", "我是测试人员");
        form.add("sex", 2);
        form.add("personId", "434332232322342332");
        form.add("dbId", "688");
        form.add("label", 1);
        form.add("deptName", "");

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(addFace, HttpMethod.POST, httpEntity, String.class);
        String body = exchange.getBody();
        System.err.println(body);

    }

    /**
     * 查询库中存在的人员
     * 请求数据
     * dbId: 688  库id
     * personName: 名字
     * personId: 编号
     * page: 1  分页开始
     * size: 16 分页结束
     * lang: zh_CN
     * 响应数据
     * {
     * "code":200,
     * "message":"查询成功",
     * "data":{
     * "pageNum":1,
     * "pageSize":16,
     * "size":1,
     * "startRow":1,
     * "endRow":1,
     * "total":1,
     * "pages":1,
     * "list":[
     * {
     * "id":12535,
     * "personId":"1111111",  //人员id
     * "imageId":"c16f55aa847f48279a9ab3b194854407",  //删除人人员使用到的照片
     * "personName":"高且", // 名字
     * "faceStoreId":"1",
     * "remark":"c16f55aa847f48279a9ab3b194854407.jpg",
     * "faceStoreName":"白名单",  //照片
     * "createTime":"2021-07-29 10:02:15",  //创建时间
     * "url":"/disk200/file/face/resource/",
     * "dbName":"工厂", //所在人员库名字
     * "dbId":682,  // 人像库id
     * "deptName":"",
     * "orgId":null,
     * "orgName":"测试设备",  // 人像库名字
     * "sex":1,
     * "extInfo":null,
     * "strelReq":0,
     * "braceletNo":null,
     * "allergy":null
     * }
     * ],
     * "prePage":0,
     * "nextPage":0,
     * "isFirstPage":true,
     * "isLastPage":true,
     * "hasPreviousPage":false,
     * "hasNextPage":false,
     * "navigatePages":8,
     * "navigatepageNums":[
     * 1
     * ],
     * "navigateFirstPage":1,
     * "navigateLastPage":1,
     * "firstPage":1,
     * "lastPage":1
     * }
     * }
     */
    public static void getFaceDBList(RestTemplate restTemplate) {
        String faceList = "https://39.108.64.200:5558/helmetBusiness/api/st/selectFaceSources";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("dbId", 688);
        form.add("personName", "");
        form.add("personId", "");
        form.add("page", 1);
        form.add("size", 16);
        form.add("lang", "zh_CN");
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(faceList, HttpMethod.POST, httpEntity, String.class);
        String body = exchange.getBody();
        System.err.println(body);
    }

    /**
     * 删除指定人脸
     * 请求数据
     * faceStoreId: 2  人脸编号
     * imageId: 4e7a2d109e0a491482d0486975369d04   图片id
     * dbId: 688 数据库ID
     * lang: zh_CN
     * 返回数据
     * {"code":200,"message":"删除成功","data":null}
     *
     * @param restTemplate
     */
    public static void delFace(RestTemplate restTemplate) {
        String delFaceUrl = "https://39.108.64.200:5558/helmetBusiness/api/st/delSingleFaceInfo";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("faceStoreId", "1");
        form.add("imageId", "38d9470c5d344cff8be2ab0c5bec6e10");
        form.add("dbId", 688);
        form.add("lang", "zh_CN");

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(delFaceUrl, HttpMethod.POST, httpEntity, String.class);
        String body = exchange.getBody();
        System.err.println(body);
    }
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------
    //-----------------------使用    终端    账号   登录---------------------------------------------
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------

    /**
     * http人脸识别
     * 请求参数
     * base64: 图片
     * district: 区域
     * address: 地区
     * device : 设备编号
     * faceId: 人脸id
     * latitude: 纬度
     * longitude：经度
     * parentId: 用户id
     * type: 人脸识别默认0
     * username: 用户名字
     * <p>
     * <p>
     * 响应结果  结果为加密结果桐乡没有加密，如果加密下面已经有解密的演示案例
     * {
     * "message":"调用成功",
     * "data":{
     * "pushId":"5A37C608A9A3090BA7DFDFA2CCD45E81",
     * "username":"27BA6E1A5A0D06BCC83888603C4C07C3",  // 报警的名字
     * "userId":"9C5248FC5F0DF6F2DCA5A28F1DBBDFD8",    // 用户id
     * "sourceImage":"06E4AC01DB94A940CDF485626C0A483E09B6A736E4100B15A89DEA6F5E3E4B0D68558016093A4F9F58867054CBD3DC27",
     * "targetImage":"E6530D509177C5ECE7FE0C22A93A0D990A297AA2FE3CB5CCC6BD50143ED17D62275671371D262F8359251B9D384736E0",
     * "similarity":"86DCB5F2D5B483CCF3658EFF3650671F",//相似度
     * "label":"B99C126F493B354821544DBA8D74AFD2",     // 标签是黑名单还是白名单  0白名单  1 黑名单
     * "deptName":"",
     * "faceId":"5A37C608A9A3090BA7DFDFA2CCD45E81",    //人脸Id
     * "imageId":"06E4AC01DB94A940CDF485626C0A483E09B6A736E4100B15A89DEA6F5E3E4B0D68558016093A4F9F58867054CBD3DC27",
     * "dbName":"9822872449F3CB6B8D48417085F1101C",    // 数据库名字
     * "userNo":"9C5248FC5F0DF6F2DCA5A28F1DBBDFD8",    // 用户编号
     * "sex":"B022958109A87E359C9335A53E1450DA",       // 性别
     * "alarmLevel":"0D7E7E51D38CD98936F46C59FEF1D6D8",
     * "extInfo":null,
     * "base64":""
     * },
     * "code":200,
     * "publicInfo":null
     * }
     */


    public static void faceAuthentication(RestTemplate restTemplate) {

        String faceUrl = "https://39.108.64.200:5558/helmetProxy/helmetProxy/api/faceRecognition";
        String fileName = "/Users/xuyihang/Downloads/测试照片.jpg";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cookie", "SESSION=" + key);
        headers.add("Content-type", "application/x-www-form-urlencoded; charset=utf-8");

        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("base64", fileToBase64(fileName));
        form.add("address", AESUtil.aesEncrypt("雁塔区软件新城二期xxx", key));
        form.add("device", AESUtil.aesEncrypt("SHGA00740", key));
        form.add("district", AESUtil.aesEncrypt("雁塔区", key));
        form.add("faceId", AESUtil.aesEncrypt("0", key));
        form.add("latitude", AESUtil.aesEncrypt("1.0", key));
        form.add("longitude", AESUtil.aesEncrypt("2.0", key));
        form.add("parentId", AESUtil.aesEncrypt("-1", key));
        form.add("regionId", AESUtil.aesEncrypt("16", key));
        form.add("type", AESUtil.aesEncrypt("0", key));
        form.add("username", AESUtil.aesEncrypt("admin", key));


        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(faceUrl, HttpMethod.POST, httpEntity, String.class);
        String body = exchange.getBody();
        String username = JSON.parseObject(body).getJSONObject("data").getString("username");
        try {
            String name = AESUtil.aesDecrypt(username, key);
            System.out.println(name);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.err.println(body);

    }

    /**
     * 查询在线的设备，可以获取实时位置
     * @param restTemplate
     */
    public static void onlineEquipment(RestTemplate restTemplate) {
        String online = "https://39.108.64.200:5558/base/user/findOnlineUserTree?lang=zh_CN";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        HttpEntity<String> requestEntity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> exchange = restTemplate.exchange(online, HttpMethod.GET, requestEntity, String.class);
        String body = exchange.getBody();
        JSONArray userList = JSON.parseObject(body).getJSONObject("data").getJSONArray("users");
        JSONObject user = userList.getJSONObject(0);
        String userNo = user.getString("userNo");

        System.err.println(userNo);

    }
    /**
     * 推送消息
     * @param restTemplate
     */
    public static void pushMasge(RestTemplate restTemplate, int type) {
        String pushM = "https://39.108.64.200:5558/helmetBusiness/api/push/msg";
        //文本框消息推送
        if (type == 2) {
            String fileName = "/Users/xuyihang/Downloads/测试照片.jpg";
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", MediaType.MULTIPART_FORM_DATA_VALUE);
            MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
            form.add("imgUrl", fileToBase64(fileName));//图片
            form.add("detailMsg", "测试信息");  // 信息
            form.add("latitude", ""); //默认
            form.add("longitude", "");//默认
            form.add("userList", "001314"); //用户名
            form.add("remark", "目的地"); // 默认
            form.add("msgType", 2);// 推送消息
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(pushM, HttpMethod.POST, httpEntity, String.class);
            String body = exchange.getBody();
            System.out.println(body);
        } else {
            //文件推送 只支持pdf
            String fileName = "/Users/xuyihang/Downloads/报销图片/03302190021116228738.pdf";
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", MediaType.MULTIPART_FORM_DATA_VALUE);
            MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
            form.add("file", new FileSystemResource(fileName)); //PDF 文件
            form.add("userList", "001314");//用户名
            form.add("fileType", "2"); // 文件默认
            form.add("msgType", 1); //推送文件
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(pushM, HttpMethod.POST, httpEntity, String.class);
            String body = exchange.getBody();
            System.out.println(body);
        }


    }

    public static String fileToBase64(String filePath) {
        byte[] bytes = null;
        try {
            FileInputStream fi = new FileInputStream(new File(filePath));
            bytes = new byte[fi.available()];
            fi.read(bytes);
            String str = Base64.getEncoder().encodeToString(bytes);
            fi.close();
            return str;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return null;

    }


}
